<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * 权限模型
 * Class Permission
 * @package app\model
 */
class Permission extends Model
{
    // 表名
    protected $name = 'permissions';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'parent_id' => 'integer',
        'sort' => 'integer',
        'status' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];
    
    /**
     * 状态获取器
     * @param $value
     * @param $data
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '禁用', 1 => '启用'];
        return $status[$data['status']] ?? '未知';
    }
    
    /**
     * 类型获取器
     * @param $value
     * @param $data
     * @return string
     */
    public function getTypeTextAttr($value, $data)
    {
        $types = [
            'menu' => '菜单',
            'button' => '按钮',
            'api' => '接口'
        ];
        return $types[$data['type']] ?? '未知';
    }
    
    /**
     * 关联角色
     * @return \think\model\relation\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, RolePermission::class, 'role_id', 'permission_id');
    }
    
    /**
     * 关联父级权限
     * @return \think\model\relation\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(Permission::class, 'parent_id', 'id');
    }
    
    /**
     * 关联子级权限
     * @return \think\model\relation\HasMany
     */
    public function children()
    {
        return $this->hasMany(Permission::class, 'parent_id', 'id');
    }
    
    /**
     * 获取权限树
     * @param array $where
     * @return array
     */
    public static function getTree(array $where = []): array
    {
        $permissions = self::where($where)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select()
            ->toArray();
            
        return self::buildTree($permissions);
    }
    
    /**
     * 构建权限树
     * @param array $permissions
     * @param int $parentId
     * @return array
     */
    public static function buildTree(array $permissions, int $parentId = 0): array
    {
        $tree = [];
        foreach ($permissions as $permission) {
            if ($permission['parent_id'] == $parentId) {
                $children = self::buildTree($permissions, $permission['id']);
                if ($children) {
                    $permission['children'] = $children;
                }
                $tree[] = $permission;
            }
        }
        return $tree;
    }
    
    /**
     * 获取所有子级权限ID
     * @param int $id
     * @return array
     */
    public static function getChildrenIds(int $id): array
    {
        $ids = [$id];
        $children = self::where('parent_id', $id)->column('id');
        
        foreach ($children as $childId) {
            $ids = array_merge($ids, self::getChildrenIds($childId));
        }
        
        return array_unique($ids);
    }
}